package com.mxx.common.data.jpa.auditing;

import com.mxx.common.spring.ApplicationContextHelper;
import org.springframework.beans.factory.InitializingBean;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

public class SpecInterceptorHandler implements InitializingBean {
    private List<SpecInterceptor> interceptors = new ArrayList<>();


    public void doSelect(SpecInterceptor.SpecState specState) {
        interceptors.forEach(p -> p.select(specState));
    }

    public void doUpdate(SpecInterceptor.SpecState specState) {
        for (SpecInterceptor interceptor : interceptors) {
            interceptor.update(specState);
            if (specState.isModify()) {
                doDelete(specState);
                return;
            }
        }
    }

    public void doDelete(SpecInterceptor.SpecState specState) {
        for (SpecInterceptor interceptor : interceptors) {
            interceptor.delete(specState);
            if (specState.isModify()) {
                doUpdate(specState);
                return;
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, SpecInterceptor> map = ApplicationContextHelper.getBeansOfType(SpecInterceptor.class);
        map.values().forEach(interceptors::add);
        interceptors.sort(Comparator.comparing(SpecInterceptor::sort));
    }
}
